#include <stdio.h>
#include <string.h>
#include <WS2tcpip.h>
#include "TcpServer.h"
TcpServer::TcpServer()
{
	m_svrSock = INVALID_SOCKET;
	m_conSock = INVALID_SOCKET;
}

TcpServer::~TcpServer()
{

}

bool TcpServer::createServer(int port)
{
	if ( !init() ) {
		return false;
	}

	m_svrSock = socket(AF_INET, SOCK_STREAM, 0);
	if (m_svrSock == INVALID_SOCKET) {
		return false;
	}

	SOCKADDR_IN svrAddr;
	svrAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
	svrAddr.sin_family = AF_INET;
	svrAddr.sin_port = htons(port);  

	bind(m_svrSock, (SOCKADDR*)&svrAddr, sizeof(SOCKADDR));
	listen(m_svrSock, 5);
	return true;
}

void TcpServer::destroyServer()
{
	exit();
}

void TcpServer::waitClient()
{
	SOCKADDR_IN addrClient;
	int len = sizeof(SOCKADDR);
	m_conSock = accept(m_svrSock, (SOCKADDR*)&addrClient, &len);
}

int TcpServer::recvData(char *buffer, const int maxSize)
{
	memset(buffer, 0, maxSize);
	int ret = recv(m_conSock, buffer, maxSize, 0);
	return ret;
}

int TcpServer::sendData(const char *buffer, const int size)
{
	int ret = send(m_conSock, buffer, size, 0);  
	return ret;
}

bool TcpServer::init()
{
	WSADATA wsaData;
	int ret = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if ( ret != 0) {
		printf("WSAStartup failed: %d\n", ret);
		return false;
	}
	return true;
}

void TcpServer::exit()
{
	if (m_svrSock != INVALID_SOCKET) {
		closesocket(m_svrSock);
	}
	if (m_conSock != INVALID_SOCKET) {
		closesocket(m_conSock);
	}
	WSACleanup();
}

